import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { isMicroAppPath, getMicroAppTabSuffix } from '../utils/microAppHelper'

export interface TitleInfo {
  rawTitle: string
  suffix?: string
  finalTitle: string
}

export const useTitleStore = defineStore('title', () => {
  // 当前页面的title信息
  const currentTitle = ref<TitleInfo>({
    rawTitle: '',
    suffix: '',
    finalTitle: ''
  })

  // 计算最终title
  const getFinalTitle = computed(() => {
    const { rawTitle, suffix } = currentTitle.value
    if (!rawTitle) return ''
    
    // 如果后缀已存在，先去掉再拼接，避免重复
    let mainTitle = rawTitle
    if (suffix && rawTitle.endsWith(' - ' + suffix)) {
      mainTitle = rawTitle.slice(0, -(' - ' + suffix).length)
    }
    
    return suffix ? `${mainTitle} - ${suffix}` : mainTitle
  })

  // 设置原始title
  const setRawTitle = (title: string) => {
    currentTitle.value.rawTitle = title
    currentTitle.value.finalTitle = getFinalTitle.value
  }

  // 设置后缀
  const setSuffix = (suffix: string) => {
    currentTitle.value.suffix = suffix
    currentTitle.value.finalTitle = getFinalTitle.value
    
    // 当设置后缀时，自动更新document.title
    // 这会触发titleObserver，进而更新tab标题
    updateDocumentTitle()
  }

  // 更新document.title - 不再直接调用，而是由titleObserver负责
  const updateDocumentTitle = () => {
    const title = getFinalTitle.value
    if (title && document.title !== title) {
      document.title = title
    }
  }

  // 获取当前title（用于tab）
  const getCurrentTitle = () => {
    return getFinalTitle.value
  }

  // 重置title
  const resetTitle = () => {
    currentTitle.value = {
      rawTitle: '',
      suffix: '',
      finalTitle: ''
    }
  }

  return {
    currentTitle,
    getFinalTitle,
    setRawTitle,
    setSuffix,
    updateDocumentTitle,
    getCurrentTitle,
    resetTitle
  }
}) 